﻿using System;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Poplar.Passport.IRepositories;
using Poplar.Passport.IServices;
using Poplar.Passport.Models;

namespace Poplar.Passport.Services
{
    public class UserService : IUserService
    {
        private readonly IUserRepository _repository;

        /// <summary>
        /// 密码盐
        /// </summary>
        private protected static readonly string Salt = "poplar";

        public UserService(IUserRepository repository)
        {
            this._repository = repository;
        }

        /// <summary>
        /// login
        /// </summary>
        /// <param name="userName">user name</param>
        /// <param name="password">password</param>
        /// <returns>login result</returns>
        public async Task<User> Login(string userName, string password)
        {
            password = Md5(Salt + password);

            return await this._repository.GetUser(userName, password);
        }

        private string Md5(string value)
        {
            using (var md5 = MD5.Create())
            {
                var result = md5.ComputeHash(Encoding.ASCII.GetBytes(value));
                var strResult = BitConverter.ToString(result);
                return strResult.Replace("-", "");
            }
        }
    }
}
